package com.leedsoft.spittr.web;

import com.alibaba.fastjson.JSON;
import com.leedsoft.spittr.exception.HomeException;
import com.leedsoft.spittr.model.User;
import com.leedsoft.spittr.model.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * Created by leeds on 2017/11/7.
 */
@Controller
@RequestMapping("home")
public class HomeController {
    @RequestMapping
    public String home(Model model) {//Model、Map，可以不用返回。
        model.addAttribute("liz", "000000");
        return "home";//在试图解析模式下，返回值为String，是逻辑视图名，用来寻找视图
    }

    @RequestMapping("test_validation")
    public String testValidation(@Valid User user, Errors errors) {
        if (errors.hasErrors()) {
            errors.getAllErrors().forEach(e -> System.out.println(e.getDefaultMessage()));
        }
        return "home";
    }

    @RequestMapping("dataBinding")
    @ResponseBody//支持对象导航（如user.name）、List列表提交（如users[0].name、users[1].name）等等。。必须封装在命令对象中
    public  String dataBinding(UserVo u) {
//        if (user.getBirthdate() == null) return "birthdate是空的";
//        System.out.println(user.getA().getLeeds());
//        return String.format("您的生日是：%tY-%1$tm-%1$td", user.getBirthdate());
        System.out.println(JSON.toJSONString(u));
        return JSON.toJSONString(u);
    }

    public static void main(String[] args) {
        System.out.println(String.format("%tY-%1$Tm-%1$Td", new Date()));
    }

    @RequestMapping("testMultipart")
    @ResponseBody
    public String testMultipart(MultipartFile file) {
        if (file == null) return "文件是空的";//测试StringHttpMessageConverter
        try {
            file.transferTo(new File("D:\\leedsjung\\test\\spring\\" + file.getOriginalFilename()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return file.getOriginalFilename();
    }

    @ResponseBody
    @RequestMapping("testHttpMessageConverter")
    public User testHttpMessageConverter() {
        User user = new User();
        user.setAge(12);
        user.setName("张力子");
        return user;
    }

    @Autowired
    private MessageSource messageSource;

    @RequestMapping(value = "testMessage", method = RequestMethod.GET)
    public String testMessage(Locale locale, Model model) {
        model.addAttribute("_locale", locale);
        model.addAttribute("ni", 111);
        System.out.println(messageSource.getMessage("age.notNull",new String[]{"章", "yike"}, locale));
        return "home";
    }

    @RequestMapping("testThymeleaf")
    public String testFormBind(@Valid User user, Errors errors, Model model) {
        model.addAttribute("tom", "cat");
        return "home";
    }

    @RequestMapping("testCustomException")
    public String testCustomException() {
        throw new HomeException();//@ResponseStatus自定义异常，返回http状态码-----REST思想。充分利用http元数据表示意思。
    }
    @RequestMapping("testCrossRedirect")
    public String testCrossRedirect(RedirectAttributes model) {//FlashAttribute 跨重定向传递数据
        model.addAttribute("tom", "testCrossRedirect2");
        model.addAttribute("jerry", 12);
        User u = new User();
        u.setAge(11);
        u.setName("张力子");
        model.addFlashAttribute("user", u);
        return "redirect:{tom}";//特别注意：重定向路径redirect:之后，不可以有空格。
    }
    @RequestMapping("testCrossRedirect2")
    @ResponseBody
    public String testCrossRedirect2(Model model, Integer jerry) {
        Map<String, Object> m = new HashMap<>();
        m.put("user", model.asMap().get("user"));//重定向到的方法，通过model，可以获取传过来的对象参数
        m.put("jerry", jerry);//但是简单参数需要通过vo获取。
        return JSON.toJSONString(m);
    }
}
